"""EDA处理器基本使用示例

演示EDA处理器的基本功能，包括：
- 基本EDA数据处理流程
- 简单峰值检测
- 指标计算
- 结果可视化

适合初学者快速上手使用。
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
import logging
from typing import Dict, Any, Optional

# 导入EDA处理器模块
from ..core.pipeline import process_eda_pipeline
from ..utils.data_io import load_eda_data, save_eda_results
from ..utils.visualization import plot_eda_signal, plot_peak_detection

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def basic_eda_processing_example(data_file: str = None, 
                               output_dir: str = None) -> Dict[str, Any]:
    """基本EDA数据处理示例
    
    演示完整的EDA数据处理流程：
    1. 加载数据
    2. 预处理
    3. 峰值检测
    4. 指标计算
    5. 质量评估
    6. 结果保存
    
    Args:
        data_file: EDA数据文件路径（可选，如果不提供则使用模拟数据）
        output_dir: 输出目录路径（可选）
        
    Returns:
        处理结果字典
    """
    print("=" * 60)
    print("EDA数据处理基本示例")
    print("=" * 60)
    
    try:
        # 1. 准备数据
        if data_file and Path(data_file).exists():
            print(f"加载数据文件: {data_file}")
            eda_data = load_eda_data(data_file)
        else:
            print("使用模拟EDA数据")
            eda_data = generate_sample_eda_data()
        
        print(f"数据长度: {len(eda_data['signal'])} 个采样点")
        print(f"采样率: {eda_data.get('sampling_rate', 4.0)} Hz")
        print(f"信号时长: {len(eda_data['signal']) / eda_data.get('sampling_rate', 4.0):.2f} 秒")
        
        # 2. 处理配置
        config = {
            'preprocessing': {
                'algorithm': 'basic',
                'params': {
                    'lowpass_freq': 1.0,
                    'outlier_threshold': 3.0,
                    'smooth_window': 5
                }
            },
            'peak_detection': {
                'algorithm': 'basic',
                'params': {
                    'height': 0.01,
                    'distance': 10,
                    'prominence': 0.005
                }
            },
            'metrics_calculation': {
                'algorithm': 'basic',
                'params': {}
            },
            'quality_assessment': {
                'algorithm': 'basic',
                'params': {}
            }
        }
        
        print("\n处理配置:")
        for step, step_config in config.items():
            print(f"  {step}: {step_config['algorithm']}")
        
        # 3. 执行处理
        print("\n开始处理...")
        results = process_eda_pipeline(eda_data, config)
        
        if not results['success']:
            print(f"处理失败: {results.get('error', '未知错误')}")
            return results
        
        # 4. 显示结果
        print("\n处理完成！")
        print_processing_results(results)
        
        # 5. 保存结果（如果指定了输出目录）
        if output_dir:
            output_path = Path(output_dir)
            output_path.mkdir(parents=True, exist_ok=True)
            
            # 保存处理结果
            results_file = output_path / "basic_processing_results.json"
            save_eda_results(results, str(results_file))
            print(f"\n结果已保存到: {results_file}")
            
            # 生成可视化图表
            create_basic_visualizations(eda_data, results, output_path)
        
        return results
        
    except Exception as e:
        logger.error(f"基本处理示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

def simple_peak_detection_example(signal: np.ndarray = None,
                                sampling_rate: float = 4.0) -> Dict[str, Any]:
    """简单峰值检测示例
    
    演示如何使用EDA处理器进行峰值检测
    
    Args:
        signal: EDA信号数组（可选）
        sampling_rate: 采样率
        
    Returns:
        峰值检测结果
    """
    print("=" * 60)
    print("EDA峰值检测示例")
    print("=" * 60)
    
    try:
        # 准备数据
        if signal is None:
            print("生成模拟EDA信号...")
            signal = generate_sample_signal_with_peaks()
        
        eda_data = {
            'signal': signal,
            'sampling_rate': sampling_rate,
            'timestamps': np.arange(len(signal)) / sampling_rate
        }
        
        # 配置峰值检测
        config = {
            'preprocessing': {
                'algorithm': 'basic',
                'params': {'lowpass_freq': 1.0}
            },
            'peak_detection': {
                'algorithm': 'improved',
                'params': {
                    'min_amplitude': 0.01,
                    'min_duration': 1.0,
                    'adaptive_threshold': True
                }
            }
        }
        
        print(f"信号长度: {len(signal)} 个采样点")
        print(f"采样率: {sampling_rate} Hz")
        
        # 执行处理
        results = process_eda_pipeline(eda_data, config)
        
        if results['success']:
            peaks = results.get('peaks', [])
            print(f"\n检测到 {len(peaks)} 个SCR峰值:")
            
            for i, peak in enumerate(peaks[:5]):  # 显示前5个峰值
                print(f"  峰值 {i+1}:")
                print(f"    时间: {peak.get('peak_time', 0):.2f}s")
                print(f"    幅度: {peak.get('amplitude', 0):.4f}")
                print(f"    持续时间: {peak.get('duration', 0):.2f}s")
            
            if len(peaks) > 5:
                print(f"  ... 还有 {len(peaks) - 5} 个峰值")
        
        return results
        
    except Exception as e:
        logger.error(f"峰值检测示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

def metrics_calculation_example(eda_data: Dict[str, Any] = None) -> Dict[str, Any]:
    """指标计算示例
    
    演示如何计算各种EDA分析指标
    
    Args:
        eda_data: EDA数据字典（可选）
        
    Returns:
        指标计算结果
    """
    print("=" * 60)
    print("EDA指标计算示例")
    print("=" * 60)
    
    try:
        # 准备数据
        if eda_data is None:
            print("生成模拟EDA数据...")
            eda_data = generate_sample_eda_data()
        
        # 配置指标计算
        config = {
            'preprocessing': {
                'algorithm': 'basic',
                'params': {}
            },
            'peak_detection': {
                'algorithm': 'basic',
                'params': {}
            },
            'metrics_calculation': {
                'algorithm': 'all',  # 计算所有可用指标
                'params': {}
            }
        }
        
        # 执行处理
        results = process_eda_pipeline(eda_data, config)
        
        if results['success']:
            metrics = results.get('metrics', {})
            print(f"\n计算了 {len(metrics)} 个指标:")
            
            # 按类别显示指标
            basic_metrics = {}
            scr_metrics = {}
            frequency_metrics = {}
            other_metrics = {}
            
            for key, value in metrics.items():
                if any(x in key.lower() for x in ['mean', 'std', 'min', 'max', 'range']):
                    basic_metrics[key] = value
                elif any(x in key.lower() for x in ['scr', 'peak', 'amplitude']):
                    scr_metrics[key] = value
                elif any(x in key.lower() for x in ['frequency', 'power', 'spectral']):
                    frequency_metrics[key] = value
                else:
                    other_metrics[key] = value
            
            if basic_metrics:
                print("\n  基本统计指标:")
                for key, value in basic_metrics.items():
                    print(f"    {key}: {value:.4f}")
            
            if scr_metrics:
                print("\n  SCR相关指标:")
                for key, value in scr_metrics.items():
                    print(f"    {key}: {value:.4f}")
            
            if frequency_metrics:
                print("\n  频域指标:")
                for key, value in frequency_metrics.items():
                    print(f"    {key}: {value:.4f}")
            
            if other_metrics:
                print("\n  其他指标:")
                for key, value in other_metrics.items():
                    print(f"    {key}: {value:.4f}")
        
        return results
        
    except Exception as e:
        logger.error(f"指标计算示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

def generate_sample_eda_data(duration: float = 300.0, 
                           sampling_rate: float = 4.0,
                           num_peaks: int = 8) -> Dict[str, Any]:
    """生成模拟EDA数据
    
    Args:
        duration: 信号时长（秒）
        sampling_rate: 采样率（Hz）
        num_peaks: SCR峰值数量
        
    Returns:
        模拟EDA数据字典
    """
    # 时间轴
    t = np.arange(0, duration, 1/sampling_rate)
    n_samples = len(t)
    
    # 基线EDA信号（缓慢变化的SCL）
    baseline = 2.0 + 0.5 * np.sin(2 * np.pi * t / 60) + 0.2 * np.sin(2 * np.pi * t / 20)
    
    # 添加噪声
    noise = np.random.normal(0, 0.02, n_samples)
    
    # 生成SCR峰值
    signal = baseline + noise
    peak_times = np.random.uniform(10, duration-10, num_peaks)
    
    for peak_time in peak_times:
        # SCR峰值参数
        amplitude = np.random.uniform(0.05, 0.3)
        rise_time = np.random.uniform(1.0, 3.0)
        recovery_time = np.random.uniform(3.0, 8.0)
        
        # 生成SCR峰值形状
        peak_indices = np.where((t >= peak_time) & (t <= peak_time + rise_time + recovery_time))[0]
        
        for i in peak_indices:
            time_from_onset = t[i] - peak_time
            
            if time_from_onset <= rise_time:
                # 上升阶段
                progress = time_from_onset / rise_time
                scr_value = amplitude * (1 - np.exp(-3 * progress))
            else:
                # 恢复阶段
                progress = (time_from_onset - rise_time) / recovery_time
                scr_value = amplitude * np.exp(-2 * progress)
            
            signal[i] += scr_value
    
    return {
        'signal': signal,
        'timestamps': t,
        'sampling_rate': sampling_rate,
        'metadata': {
            'duration': duration,
            'num_simulated_peaks': num_peaks,
            'description': '模拟EDA数据，包含基线漂移、噪声和SCR峰值'
        }
    }

def generate_sample_signal_with_peaks(duration: float = 120.0,
                                    sampling_rate: float = 4.0) -> np.ndarray:
    """生成包含明显峰值的模拟信号"""
    t = np.arange(0, duration, 1/sampling_rate)
    
    # 基线信号
    baseline = 1.5 + 0.3 * np.sin(2 * np.pi * t / 30)
    
    # 添加几个明显的SCR峰值
    signal = baseline.copy()
    peak_times = [20, 45, 70, 95]
    
    for peak_time in peak_times:
        amplitude = np.random.uniform(0.1, 0.4)
        width = np.random.uniform(8, 15)
        
        # 高斯形状的峰值
        peak_signal = amplitude * np.exp(-0.5 * ((t - peak_time) / (width/4))**2)
        signal += peak_signal
    
    # 添加噪声
    noise = np.random.normal(0, 0.01, len(signal))
    signal += noise
    
    return signal

def print_processing_results(results: Dict[str, Any]):
    """打印处理结果摘要"""
    print("\n处理结果摘要:")
    print("-" * 40)
    
    # 预处理结果
    if 'preprocessed_signal' in results:
        original_length = len(results.get('original_signal', []))
        processed_length = len(results['preprocessed_signal'])
        print(f"预处理: 完成 ({original_length} -> {processed_length} 个采样点)")
    
    # 峰值检测结果
    if 'peaks' in results:
        peak_count = len(results['peaks'])
        print(f"峰值检测: 检测到 {peak_count} 个SCR峰值")
        
        if peak_count > 0:
            amplitudes = [p.get('amplitude', 0) for p in results['peaks']]
            avg_amplitude = np.mean(amplitudes)
            print(f"  平均峰值幅度: {avg_amplitude:.4f}")
    
    # 指标计算结果
    if 'metrics' in results:
        metrics_count = len(results['metrics'])
        print(f"指标计算: 计算了 {metrics_count} 个指标")
        
        # 显示关键指标
        metrics = results['metrics']
        if 'mean_eda' in metrics:
            print(f"  平均EDA: {metrics['mean_eda']:.4f}")
        if 'scr_count' in metrics:
            print(f"  SCR数量: {metrics['scr_count']}")
    
    # 质量评估结果
    if 'quality_assessment' in results:
        quality = results['quality_assessment']
        overall_score = quality.get('overall_score', 0)
        print(f"质量评估: {overall_score:.2f}/1.0")
        
        # 显示质量问题
        issues = quality.get('issues', [])
        if issues:
            print(f"  发现 {len(issues)} 个质量问题")

def create_basic_visualizations(eda_data: Dict[str, Any], 
                              results: Dict[str, Any], 
                              output_dir: Path):
    """创建基本可视化图表"""
    try:
        # EDA信号图
        signal_fig = plot_eda_signal(
            eda_data['signal'],
            eda_data.get('timestamps'),
            title="EDA信号 - 基本处理示例"
        )
        signal_fig.savefig(output_dir / "eda_signal.png", dpi=300, bbox_inches='tight')
        plt.close(signal_fig)
        
        # 峰值检测图
        if 'peaks' in results and results['peaks']:
            peaks_fig = plot_peak_detection(
                eda_data['signal'],
                results['peaks'],
                eda_data.get('timestamps'),
                title="峰值检测结果 - 基本处理示例"
            )
            peaks_fig.savefig(output_dir / "peak_detection.png", dpi=300, bbox_inches='tight')
            plt.close(peaks_fig)
        
        print(f"可视化图表已保存到: {output_dir}")
        
    except Exception as e:
        logger.warning(f"创建可视化图表失败: {str(e)}")

# 主函数示例
if __name__ == "__main__":
    print("EDA处理器基本使用示例")
    print("=" * 60)
    
    # 运行基本处理示例
    print("\n1. 基本EDA数据处理示例")
    basic_results = basic_eda_processing_example(output_dir="./output/basic_example")
    
    # 运行峰值检测示例
    print("\n2. 峰值检测示例")
    peak_results = simple_peak_detection_example()
    
    # 运行指标计算示例
    print("\n3. 指标计算示例")
    metrics_results = metrics_calculation_example()
    
    print("\n所有示例运行完成！")